package filehelp

import (
	"bytes"
	"encoding/csv"
	"errors"
	"github.com/gin-gonic/gin"
	"os"
	"path/filepath"
)

type CsvWriter struct {
	buffer *bytes.Buffer
	writer *csv.Writer
}

func (c *CsvWriter) New() {
	c.buffer = &bytes.Buffer{}
	c.buffer.WriteString("\xEF\xBB\xBF")
	c.writer = csv.NewWriter(c.buffer)
}

func (c *CsvWriter) Write(record []string) error {
	if c.writer == nil {
		return errors.New("writer not initialized")
	}
	return c.writer.Write(record)
}

func (c *CsvWriter) SaveToFile(dir, fileName string) (err error) {
	if c.writer == nil {
		return errors.New("writer not initialized")
	}
	c.writer.Flush()
	if err = os.MkdirAll(dir, os.ModePerm); err != nil {
		return
	}
	filePath := filepath.Join(dir, fileName)
	file, err := os.Create(filePath)
	if err != nil {
		return err
	}
	defer file.Close()
	_, err = file.Write(c.buffer.Bytes())
	return err
}

func (c *CsvWriter) SaveToGinResponse(ctx *gin.Context, fileName string) (err error) {
	ctx.Header("Content-Type", "application/csv")
	ctx.Header("Content-Disposition", "attachment;filename="+fileName)
	c.writer.Flush()
	_, err = ctx.Writer.Write(c.buffer.Bytes())
	return
}
